import React, { useCallback } from 'react';
import { FilePond, registerPlugin } from 'react-filepond';
import 'filepond/dist/filepond.min.css';
import 'filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css';

import FilePondPluginImagePreview from 'filepond-plugin-image-preview';
import FilePondPluginFileValidateType from 'filepond-plugin-file-validate-type';

registerPlugin(FilePondPluginImagePreview, FilePondPluginFileValidateType);

interface FileUploaderProps {
  onSelectFileResult: (file: File) => void;
}

const FileUploader: React.FC<FileUploaderProps> = ({ onSelectFileResult }) => {
  // 处理文件上传
  const handleProcess = useCallback(
    (
      _fieldName: string,
      file: Blob,
      _metadata: any,
      load: (uniqueFileId: string) => void
    ) => {
      if (file instanceof File) {
        onSelectFileResult(file);
      }
      load(file instanceof File ? file.name : 'uploaded-file');
    },
    [onSelectFileResult]
  );

  return (
    <FilePond
      name="file"
      labelIdle='拖放文件或 <span class="filepond--label-action"> 选择文件 </span>'
      allowMultiple={false}
      acceptedFileTypes={['application/octet-stream']}
      server={{ process: handleProcess }}
      onprocessfile={(error) => {
        if (!error) console.info('文件处理完成.');
      }}
    />
  );
};

export default FileUploader;
